package com.saifan.wyy_ov.ui.communitylife;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.FleaMarketRequstBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.property.CommentsPicAdapter;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.BootstrapButton;
import com.saifan.wyy_ov.ui.view.NoScrollGridView;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.PictureUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-11 21:10:47
 * @descrption 跳蚤市场发布
 */

public class FleamarkReleaseActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener, TextWatcher {
    private Toolbar toolbar;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private RadioButton radioButton3;

    private BootstrapButton release;
    private RadioGroup radiogroup;

    private EditText BT;
    private EditText JE;
    private EditText LXR;
    private EditText LXDH;
    private EditText XXQK;
    private NoScrollGridView picgrid;

    private RoomInfoBean roomInfoBean;
    private ArrayList<String> selectList = new ArrayList<>();
    private CommentsPicAdapter adapter;
    private final int SELECT_IMG = 0;
    private final int SELECT_PHOTO_TAKEPHOTO = 1;
    private static final int CHOSE_CONTACTS = 1234;
    private String picName = "";
    private int selectPostion = 0;
    int LX = 1;
    float price = 0;
    private LinearLayout layoutprive;
    private ImageView diver;
    private TextView textCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
        setContentView();

    }

    public void setContentView() {
        setContentView(R.layout.activity_fleamark_release);
        this.textCount = (TextView) findViewById(R.id.textCount);
        this.diver = (ImageView) findViewById(R.id.diver);
        this.layoutprive = (LinearLayout) findViewById(R.id.layout_prive);
        this.picgrid = (NoScrollGridView) findViewById(R.id.pic_grid);
        this.XXQK = (EditText) findViewById(R.id.XXQK);
        this.LXDH = (EditText) findViewById(R.id.LXDH);
        this.LXR = (EditText) findViewById(R.id.LXR);
        this.JE = (EditText) findViewById(R.id.JE);
        this.BT = (EditText) findViewById(R.id.BT);
        this.radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
        this.release = (BootstrapButton) findViewById(R.id.release);
        this.radioButton3 = (RadioButton) findViewById(R.id.radioButton3);
        this.radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
        this.radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
        radioButton1.setTextColor(Color.RED);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        radioButton1.setOnCheckedChangeListener(this);
        radioButton2.setOnCheckedChangeListener(this);
        radioButton3.setOnCheckedChangeListener(this);

        if(roomInfoBean!=null){
            LXR.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_LC()));
            LXDH.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_SJ()));
        }

        XXQK.addTextChangedListener(this);
        adapter = new CommentsPicAdapter(selectList, FleamarkReleaseActivity.this);
        picgrid.setAdapter(adapter);
        picgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (selectList.size() < 5) {
                    selectPostion = position - 1;
                    showSelectImgDialog(position == 0 ? false : true, position - 1);
                } else {
                    selectPostion = position;
                    showSelectImgDialog(true, position);
                }
            }
        });
    }

    private String initParams() {
        FleaMarketRequstBean requestBean = new FleaMarketRequstBean();
        requestBean.setXMBS(getRoomInfoBean().getXMBS());
        requestBean.setTZSC_BT(BT.getText().toString().trim());
        requestBean.setTZSC_LX(LX);

        if (LX == 1) {
            requestBean.setTZSC_JE(Float.valueOf(JE.getText().toString()));
        }

        requestBean.setTZSC_KHWJ(roomInfoBean.getWYKHDA_ZJ());
        requestBean.setTZSC_LXR(LXR.getText().toString());
        requestBean.setTZSC_LXDH(LXDH.getText().toString());
        requestBean.setTZSC_XXQK(XXQK.getText().toString());

        return new Gson().toJson(requestBean);
    }


    public void submit(View view) {
        if (isEmpty(BT)) {
            ToastUtil.showToast(this, "标题不能为空");

            return;
        }
        if (LX == 1) {
            if (isEmpty(JE)) {
                ToastUtil.showToast(this, "价格不能为空");
                return;
            }
        }
        if (isEmpty(LXR)) {
            ToastUtil.showToast(this, "联系人不能为空");

            return;
        }
        if (isEmpty(LXDH)) {
            ToastUtil.showToast(this, "联系人电话不能为空");

            return;
        }


        GetData getData = new GetData();
        RequestParams params = new RequestParams();
        params.addBodyParameter(Api.FleaMarket.FLEA_MARKET, initParams());
        for (int i = 0; i < selectList.size(); i++) {
            File file = new File(PictureUtil.getCompressBitmap(selectList.get(i)));
            if (file.exists()) {
                LogUtil.i(FileUtils.getFileSize(FileUtils.getFileSize(file.getPath())));
                params.addBodyParameter(file.getName(), file);
            }

        }

        getData.getData(Api.FleaMarket.FLEA_MARKET_INFO_SUBMIT, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                DialogUtil.showProgressDialog(FleamarkReleaseActivity.this, "正在提交");
            }

            @Override
            public void onCancelled() {
                super.onCancelled();
                LogUtil.i("取消请求");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (!StringUtil.isNullOrEmpty(responseInfo.result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        String code = jsonObject.getString("Code");
                        if (code.equals("200")) {
                            ToastUtil.showToast(FleamarkReleaseActivity.this, "提交成功");
                            DialogUtil.closeProgressDialog();
                            finish();

                        } else if (code.equals("202")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(FleamarkReleaseActivity.this, "保存失败，信息未做修改 !");
                        } else {
                            LogUtil.e(code);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    LogUtil.e("ServerError");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.i(s);
                ToastUtil.showToast(FleamarkReleaseActivity.this, getString(R.string.network_error));
                DialogUtil.closeProgressDialog();
            }

        });
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            buttonView.setTextColor(Color.RED);
            if (buttonView.getId() == R.id.radioButton1) {
                LX = 1;
                diver.setVisibility(View.VISIBLE);
                layoutprive.setVisibility(View.VISIBLE);
            } else if (buttonView.getId() == R.id.radioButton2) {
                diver.setVisibility(View.GONE);
                layoutprive.setVisibility(View.GONE);
                LX = 2;
            } else if (buttonView.getId() == R.id.radioButton3) {
                diver.setVisibility(View.GONE);
                layoutprive.setVisibility(View.GONE);
                LX = 3;
            }


        } else {
            buttonView.setTextColor(Color.BLACK);
        }


    }

    public void getContacts(View view) {


        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS }, CHOSE_CONTACTS);
                return;
            }else {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, CHOSE_CONTACTS);
            }
        }else {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, CHOSE_CONTACTS);
        }

    }

    public void selectImg() {
        storePermission(SELECT_IMG);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == SELECT_IMG) {
            if (resultCode == RESULT_OK) {
                this.selectList = data.getStringArrayListExtra("data");
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (resultCode == RESULT_OK) {
                Bitmap bitmap = data.getParcelableExtra("data") ;
                File file = FileUtils. bitmapToFile(bitmap);
                FileUtils.toAlbum(this,file);
                picName=file.getAbsolutePath();
                if (selectPostion == -1) {
                    this.selectList.add(picName);
                } else {
                    this.selectList.set(selectPostion, picName);
                }
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == CHOSE_CONTACTS) {
            if (!(resultCode == RESULT_OK)) {
                return;
            }
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            String name = "";
            String number = "";
            Cursor cursor = getContentResolver().query(uri, null, null, null,
                    null);
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
                        name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                            if (phones.moveToFirst()) {
                                //遍历所有的电话号码
                                number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            }
                        }
//
                        LXDH.setText(StringUtil.returnShow(number.replace(" ","")));
                        LXR.setText(StringUtil.returnShow(name));
                    }

                } catch (Exception e) {
                    LogUtil.e(e.toString());
                } finally {
                    cursor.close();
                }
            }
        }
    }

    //显示选择图片的对话框
    private void showSelectImgDialog(boolean hasDelete, final int deletePostion) {
        String[] items;
        if (hasDelete)
            items = new String[]{"从相册中选择", "拍照", "删除"};
        else
            items = new String[]{"从相册中选择", "拍照"};


        AlertDialog dialog = new AlertDialog.Builder(FleamarkReleaseActivity.this)
                .setTitle("选择图片")

                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            selectImg();
                        } else if (which == 2) {
                            selectList.remove(deletePostion);
                            adapter.list = selectList;
                            adapter.notifyDataSetChanged();
                        } else {
                         cammerPermission(SELECT_PHOTO_TAKEPHOTO);
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    public void cammerPermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, position);
                return;
            } else {


                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            }
        } else {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


        }

    }

    public void storePermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, position);
                return;
            } else {
                Intent intent = new Intent(this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                startActivityForResult(intent, SELECT_IMG);
            }
        } else {
            Intent intent = new Intent(this, PhotoAlbumActivity.class);
            intent.putStringArrayListExtra("data", selectList);
            startActivityForResult(intent, SELECT_IMG);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用摄像头", Toast.LENGTH_SHORT)
                        .show();

            }
        } else
            if (requestCode==CHOSE_CONTACTS){

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(i, CHOSE_CONTACTS);


                } else {
                    // Permission Denied
                    Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                            .show();

                }


        }
        else {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                this.startActivityForResult(intent, SELECT_IMG);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用本地存储读写", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        textCount.setText(s.length() + "/180");
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
